package com.cs.study.homework._0307;

public class Demo2 {
    public static void main(String[] args) {
        DownLoad downLoad = new DownLoad();
        Thread t1 = new Thread(downLoad);
        Thread t2 = new Thread(downLoad);
        Thread t3 = new Thread(downLoad);
        t1.setName("迅雷1");
        t2.setName("迅雷2");
        t3.setName("迅雷3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class DownLoad implements Runnable {
    //定义变量
    int m = 100;
    //定义锁
    Object o = new Object();
    int i = 0;

    @Override
    public void run() {
        while (true) {
            if (i % 3 == 0) {
                synchronized (o) {
                    if (m > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(Thread.currentThread().getName() + "下载剩余" + m-- + "MB");
                    }
                }
            } else {
                load();
            }
            i++;
        }
    }


    public synchronized void load() {
        if (m > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "下载剩余" + m-- + "MB");
        }
    }
}
